<template>
  <div class="tree">
    <a-row :gutter="8">
      <a-col :span="8">
        <a-card title="树形结构" style="width: 100%">
          <!-- <a slot="extra" href="#">more</a>
          <p>card content</p>
          <p>card content</p>
          <p>card content</p> -->
          <div class="content">
            <a-row>
              <a-select default-value="显示状态" style="width: 120px" @change="handleSelectChange">
                <a-select-option v-for="(item,index) in selectType" :value="item" :key="'select_'+index">
                  {{item}}
                </a-select-option>
              </a-select>
              <a-input-search placeholder="搜索" v-model="searchText" style="width: 200px" @change="handleInputChange" />
              <a-button icon="plus" type="primary" @click="handleAddFile">
                添加一级文件夹
              </a-button>
            </a-row>
            <a-tree
              v-model="checkedKeys"
              :tree-data="tableData"
              draggable
              @drop="onDrop"
              @select="onSelect"
              :defaultExpandAll="isAutoExpandParent"
              @dragenter="onDragEnter"
              rightClick="getrightClick"
              :showLine="isShowLine">
              <div slot="title">123123</div>
            </a-tree>
          </div>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card title="文件管理" style="width: 100%">
          <a-upload
            name="file"
            slot="extra"
            :showUploadList="false"
            :beforeUpload="beforeUploadFile">
            <a-button> <a-icon type="upload" />文件上传</a-button>
          </a-upload>
          <a-list item-layout="horizontal" :data-source="fileList">
            <a-list-item slot="renderItem" slot-scope="item, index">
              {{item}}
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
    <a-modal
      title="添加文件夹"
      :visible="visible"
      okText="确定"
      cancelText="取消"
      @ok="handleAddFileOK"
      @cancel="handleAddFileCancel">
      <div>
        <a-input placeholder="请输入文件夹名称" v-model="fileName"></a-input>
      </div>
    </a-modal>
  </div>
</template>

<script>
export default {
  props: ['treeData'],
  data () {
    return {
      tableData: [],
      selectType: ['展开全部','折叠全部'],
      selected: '',
      isShowLine: true,
      isAutoExpandParent: true,
      checkedKeys: [],
      searchText: '',
      visible: false,
      fileName: '',
      fileList: [],
      selectFile: {},
      currentPid: '',
      currentFile: {},
      dataList: []
    }
  },
  watch: {
    visible(newValue){
      if(newValue == false)this.fileName = ''
    },
    treeData: {
      deep: true,  // 深度监听
      handler(newVal,oldVal) {
        this.tableData = newVal
        console.log(newVal)
      }
    }
  },
  mounted(){
    this.tableData = this.treeData
    this.generateList(this.tableData)
  },
  methods: {
    handleSelectChange(value){
      if(value === '展开全部'){
        this.isAutoExpandParent = true
      }else{
        this.isAutoExpandParent = false
      }
      
    },
    handleInputChange(e){
      const value = e.target.value;
      const expandedKeys = this.tableData
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return this.getParentKey(item.key, this.tableData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
    handleAddFile(){
      this.visible = true
    },
    handleAddFileOK(){
      this.visible = false
      var tableData = this.tableData
      var arr = {
        id: this.tableData[this.tableData.length-1].id+1, // id自增
        title: this.fileName,
        key: this.fileName,
        children: [],
        files: ['411595325075_.png','抽奖1–扫明码.png','411595325075_.png','30091da4fc6e4eedb0a78847e9f4cce2.png'],
      }
      tableData.push(arr)
      this.$emit('getNewTree',tableData)
    },
    handleAddFileCancel(){
      this.visible = false
    },
    getrightClick(e){
      console.log(e)
    },
    onDragEnter(info) {
      console.log(info);
      // expandedKeys 需要受控时设置
      // this.expandedKeys = info.expandedKeys
    },
    onDrop(info) {
      const dropKey = info.node.eventKey;
      const dragKey = info.dragNode.eventKey;
      const dropPos = info.node.pos.split('-');
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr);
          }
          if (item.children) {
            return loop(item.children, key, callback);
          }
        });
      };
      const data = [...this.tableData];

      // Find dragObject
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj);
        });
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj);
        });
      } else {
        let ar;
        let i;
        loop(data, dropKey, (item, index, arr) => {
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
      }
      // 更新pid
      for(let i in data){
        for(let j in data[i].children){
          data[i].children[j].pid = data[i].id
        }
      }
      this.$emit('getNewTree',data) // 更新数组
      this.tableData = data
    },
    onSelect(key,e){
      let tableData = this.tableData
      var that = this
      that.fileList = []
      function searchChildFiles(arr){
        // 判断是不是顶级
        // console.log(arr)
        if(arr.children.length != 0 && arr.children){
          for(let i in arr.children){
            searchChildFiles(arr.children[i])
          }
        }
        
        for(let i in arr.files){
          that.fileList.push(arr.files[i])
        }
      }
      function searchObj(arr){
        for(let i in arr){
          // console.log(arr[i])
          if(arr[i].key.indexOf(key[0]) != -1){
            // 获取到当前选中的选项
            that.selectFile = arr[i]
            searchChildFiles(arr[i])
          }else{
            searchObj(arr[i].children)
          }
        }
      }
      searchObj(tableData)
    },
    beforeUploadFile(file,fileList){
      if(this.selectFile.length == 0 || !this.selectFile.files){
        this.$message.warning('请先选择需要上传的文件夹');
        return false
      }
      for(let i in fileList){
        this.selectFile.files.push(fileList[i].name)
        this.fileList.push(fileList[i].name)
        searchObj(tableData,fileList[i].name)
      }
      let tableData = this.tableData
      var that = this
      function searchObj(arr,name){
        for(let i in arr){
          if(arr[i].key.indexOf(that.selectFile.key) != -1){
            // 获取到当前选中的选项
            arr[i].files.push(name)
          }else{
            searchObj(arr[i].children)
          }
        }
      }
      this.$emit('getNewTree',tableData)
      this.$message.success('上传成功');
    },
    generateList(data){
      var that = this
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        that.dataList.push({ key, title: key });
        if (node.children) {
          that.generateList(node.children);
        }
      }
    },
    getParentKey(key,tree){
      let parentKey;
      var that = this
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          console.log(node.children)
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (that.getParentKey(key, node.children)) {
            
            parentKey = that.getParentKey(key, node.children);
          }
        }
      }

      return parentKey;
    }
  }
}
</script>

<style scoped>

</style>
